package com.study.springboot.common.util;

import com.study.springboot.common.constant.BaseRespStatus;
import com.study.springboot.common.constant.GlobalConsts;
import com.study.springboot.common.mvc.RespData;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 响应工具类
 *
 * @author wei.zhao
 * @date 2021年11月30日 11:26
 */
@Component
public class WebUtil {

    /**
     * 获取请求
     */
    public static HttpServletRequest getCurRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();
    }

    /**
     * 获取响应
     */
    public static HttpServletResponse getCurResponse() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getResponse();
    }

    /**
     * 获取当前客户端TOKEN
     */
    public static final String getCurToken() {
        return getCurRequest().getHeader(GlobalConsts.TOKEN_HEADER);
    }

    /**
     * 获取当前用户ID
     */
    public static Long getCurUserId() {
        String token = getCurToken();
        Claims claims = JwtTokenUtil.getClaimsFromToken(token, GlobalConsts.JWT_SECRET);
        Long id = (Long) claims.get(GlobalConsts.ID);
        //TODO 校验id是否存在
        return id;
    }

    /**
     * 公共响应,无返回值
     */
    public static <T> RespData<T> callback(BaseRespStatus baseRespStatus) {
        return callback(baseRespStatus, null);
    }

    /**
     * 公共响应,有返回值
     */
    public static <T> RespData<T> callback(BaseRespStatus baseRespStatus, T data) {
        return callback(baseRespStatus.getCode(), baseRespStatus.getMessage(), data);
    }

    /**
     * 公共响应,有返回值；message可拼接参数
     */
    public static <T> RespData<T> callback(BaseRespStatus baseRespStatus, T data, String... args) {
        return callback(baseRespStatus.getCode(), String.format(baseRespStatus.getMessage(), args), data);
    }

    /**
     * 公共响应,有返回值
     */
    public static <T> RespData<T> callback(Integer code, String message, T data) {
        return new RespData<T>(code, message, data);
    }

}
